package com.egao.common.core.security;

import cn.hutool.core.util.IdUtil;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentInfo;
import com.egao.common.module.student.service.StudentInfoService;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.system.constants.UserConstants;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * CAS用户登录操作
 *
 * @author system
 */
@Component
public class CasUserDetailServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

    @Autowired
    private UserService userService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentInfoService studentInfoService;

    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken casAssertionAuthenticationToken) throws UsernameNotFoundException {
        //由于登录交于cas服务端管理，如果进入这里代表登录成功
        String username = casAssertionAuthenticationToken.getName();
        User user = userService.getByUsername(username);

        // 没有找到单点登录用户 为该用户初始一个学生用户角色
        if (user == null) {
            String pwd = IdUtil.simpleUUID();

            User insert = new User();
            insert.setUsername(username);
            insert.setPassword(userService.encodePsw(pwd));
            insert.setName(username);
            insert.setState(0);
            insert.setCas(UserConstants.CAS_TRUE);
            user = userService.saveUserStudent(insert);

            if (user == null) {
                throw new UsernameNotFoundException("Username Not Found");
            }

            Student student = new Student();
            student.setUserId(user.getUserId());
            student.setXh(username);
            student.setXm(username);

            if (studentService.save(student)) {
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setUserId(user.getUserId());
                studentInfo.setStudentId(student.getId());
                studentInfo.setXh(username);
                studentInfoService.save(studentInfo);
            }

        }
        user.setState(UserConstants.STATE);
        return userService.selectUserAuth(user);
    }
}
